package com.tender.util;

import cn.hutool.json.JSONUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import com.tender.domain.ShiroUser;


/**
 * shiro工具类
 * 经过反复斟酌，最后还是把 ShiroUtil 放到 service 模块
 *
 * @author cuisudong
 */
public class ShiroUtil {

    /**
     * @Description 获得shiro的session
     */
    public static Session getShiroSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * @Description 获得shiro的sessionId
     */
    public static String getShiroSessionId() {
        return getShiroSession().getId().toString();
    }

    /**
     * @Description 是否登陆
     */
    public static Boolean isAuthenticated() {
        Subject subject = SecurityUtils.getSubject();
        return subject.isAuthenticated();
    }

    public static ShiroUser getShiroUser() {
        Subject subject = SecurityUtils.getSubject();
        if (null != subject && null != subject.getPrincipal()) {
            // 两个 ClassLoader 不一样，所以只能这样
            return JSONUtil.toBean(JSONUtil.toJsonStr(subject.getPrincipal()), ShiroUser.class);
        }

        return null;
    }
}
